package com.feature.learn.hutool;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class HmacTestURLEncodeData {


    public static void main(String[] args) {
        HttpRequest post = HttpUtil.createPost("http://139.159.132.10:8282/openapi/admin/eosd/remark");

        String sk = "pzvk5krfyb1kifc9yj0j7888uyi9djzpihfkgpmqr84dnsgkf5njfe05s3rpf9m2";
        String ak = "zfeih634wfg89gheh04n419tkc0viue";
        String queryStr="";
        String date = "Mon, 15 Mar 2021 11:47:21 GMT";
        String uri="/openapi/admin/eosd/remark";

        String body = "actionId=EOSD_010XA01123_20210409140649&message=test";
        String sha256 = getSHA256(body);
        System.out.println("digest:"+sha256);

        StringBuffer sb = new StringBuffer();
        sb.append("Date:");
        sb.append(date);
        sb.append("\n");
        sb.append("POST");
        sb.append(" ");
        sb.append(uri);
        if (StringUtils.isNotEmpty(queryStr)) {
            sb.append(" ");
            sb.append(queryStr);
        }
        sb.append(" HTTP/1.1");
        sb.append("\n");
        sb.append("Digest:");
        sb.append(sha256);
        String signatureStr = sb.toString();
        HMac hMac = new HMac(HmacAlgorithm.HmacSHA256, sk.getBytes());
        String signature = hMac.digestHex(signatureStr);

        System.out.println(signatureStr);
        System.out.println("signature:"+signature);

        Map<String, String> header = new HashMap<>();
        header.put("Digest", sha256);
        header.put("Date", date);
        header.put("Signature", signature);
        header.put("Authorization-Type", "HMAC");
        header.put("AccessKey", ak);
        post.addHeaders(header);
        post.body(body, "application/json");
        HttpResponse execute = post.execute();
        System.out.println(execute.toString());
    }

    /**
     * @Description:获取SHA256摘要
     * @Author: hql
     * @Param:
     * @Return:
     * @Date: 2021/3/8 8:51 下午
     **/
    public static String getSHA256(String data) {
        return SecureUtil.sha256(data);
    }

}
